/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.button.validator.ButtonValidateParam;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.history.HistoricProcessInstance;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.*;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;
import com.je.bpm.engine.repository.Model;
import com.je.bpm.engine.repository.ModelQuery;
import com.je.bpm.engine.runtime.Execution;
import com.je.bpm.engine.task.IdentityLinkType;
import com.je.bpm.engine.task.Task;
import com.je.bpm.engine.task.TaskInfo;
import com.je.bpm.engine.task.TaskQuery;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 根据流程绑定的funcCode获取流程未时可展示的按钮
 */
public class GetTaskButtonVariableCmd implements Command<ButtonValidateParam>, Serializable {


    //挂起
    private static final int SUSPENSION_STATE = 2;

    private static final long serialVersionUID = 1L;
    private ButtonValidateParam buttonValidateParam;

    public GetTaskButtonVariableCmd(ButtonValidateParam buttonValidateParam) {
        this.buttonValidateParam = buttonValidateParam;
    }

    @Override
    public ButtonValidateParam execute(CommandContext commandContext) {
        return getButtonVariableInstanceEntity(commandContext);
    }

    private ButtonValidateParam getButtonVariableInstanceEntity(CommandContext commandContext) {
        //获取taskIds
        Set<String> taskIds = getLogUserTaskIdsByBeanId(commandContext);
        if (taskIds.size() > 0) {
            //设置按钮变量
            //会签多人节点，并行审批会创建多个task，多个task他们的前置节点处理人是同一个，按钮变量会有多个
            List<Task> list = buttonValidateParam.getTaskList();
            List<VariableInstanceEntity> variableInstanceEntityList = new ArrayList<>();
            for (Task task : list) {
                TaskEntityImpl taskEntity = (TaskEntityImpl) task;
                Map<String, VariableInstanceEntity> map = taskEntity.getVariableInstanceEntities();
                for (String key : map.keySet()) {
                    variableInstanceEntityList.add(map.get(key));
                }
                //会签节点的taskConfigs变量，存在父级execution里面
                if (task.getTaskDefinitionKey().startsWith("countersign") || task.getTaskDefinitionKey().startsWith("batchtask")) {
                    Map<String, VariableInstance> parentVar = taskEntity.getExecution().getVariableInstances();
                    VariableInstanceEntity variableInstanceEntity = (VariableInstanceEntity) parentVar.get("taskConfigs");
                    variableInstanceEntity.setTaskId(task.getId());
                    variableInstanceEntityList.add(variableInstanceEntity);
                }
            }
            buttonValidateParam.buttonVariableList(variableInstanceEntityList);
        }
        //设置流程启动和结束状态
        List<Execution> executionList = commandContext.getProcessEngineConfiguration().getRuntimeService()
                .createExecutionQuery().processInstanceBusinessKey(buttonValidateParam.getBeanId()).list();
        //流程实例大于0说明已经启动
        if (executionList.size() > 0) {
            buttonValidateParam.starting(true);
        }

        for (Execution execution : executionList) {
            ExecutionEntity executionEntity = (ExecutionEntity) execution;
            if (executionEntity.getSuspensionState() == SUSPENSION_STATE) {
                buttonValidateParam.hang(true);
            }
        }

        //没有启动，并且历史数据大于0，并且说明已经结束
        if (!buttonValidateParam.getStarting()) {
            List<HistoricProcessInstance> historicProcessInstanceList = commandContext.getProcessEngineConfiguration().getHistoryService()
                    .createHistoricProcessInstanceQuery()
                    .processInstanceBusinessKey(buttonValidateParam.getBeanId()).list();
            if (historicProcessInstanceList.size() > 0) {
                buttonValidateParam.ending(true);
            }
        }
        //如果未启动获取所有的bpmModel
        if (buttonValidateParam.getStarting() == false && buttonValidateParam.getEnding() == false) {
            getKeysByFuncCode(commandContext);
        }
        return buttonValidateParam;
    }

    /**
     * 根据beanId获取当前登陆人的任务按钮配置信息
     *
     * @param commandContext
     * @return
     */
    private Set<String> getLogUserTaskIdsByBeanId(CommandContext commandContext) {
        List<BpmnModel> modelList = new ArrayList<>();
        //根据beanId,获取task信息
        TaskQuery taskQuery = commandContext.getProcessEngineConfiguration().getTaskService().createTaskQuery();
        taskQuery.processInstanceBusinessKey(buttonValidateParam.getBeanId());
        Set<String> taskIds = new HashSet<>();
        List<Task> taskEntityList = taskQuery.list();
        List<Task> currentTaskEntityList = new ArrayList<>();

        HashMap<String, Task> map = new HashMap<>();
        List<Task> multiTaskList = new ArrayList<>();
        List<Task> assigneeTaskList = new ArrayList<>();
        //当前登录人id
        String logUserId = Authentication.getAuthenticatedUser().getDeptId();
        for (Task task : taskEntityList) {
            String taskDefinitionKey = task.getTaskDefinitionKey();
            if (!Strings.isNullOrEmpty(taskDefinitionKey) && map.get(taskDefinitionKey) == null) {
                map.put(taskDefinitionKey, task);
            } else {
                multiTaskList.add(task);
            }
            String assignee = task.getAssignee();
            if (logUserId.equals(assignee)) {
                assigneeTaskList.add(task);
            }
        }
        List<Task> multiTaskListNew = new ArrayList<>();
        if (multiTaskList.size() > 0) {
            for (Task task : multiTaskList) {
                if (map.get(task.getTaskDefinitionKey()) != null) {
                    multiTaskListNew.add(map.get(task.getTaskDefinitionKey()));
                    map.remove(task.getTaskDefinitionKey());
                }
            }
        }
        multiTaskListNew.addAll(multiTaskList);
        multiTaskListNew.removeAll(assigneeTaskList);
        taskEntityList.removeAll(multiTaskListNew);
        taskEntityList.removeAll(assigneeTaskList);
        if (assigneeTaskList.size() > 0) {
            for (Task task : assigneeTaskList) {
                taskIds.add(task.getId());
                if (modelList.size() == 0) {
                    modelList.add(ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId()));
                }
                currentTaskEntityList.add(task);
            }
        }

        if (multiTaskListNew.size() > 0) {
            if (assigneeTaskList.size() > 0) {
                List<Task> distinctTaskLists = new ArrayList<>();
                for (Task task : assigneeTaskList) {
                    for (Task multiTask : multiTaskListNew) {
                        if (task.getTaskDefinitionKey().equals(multiTask.getTaskDefinitionKey())) {
                            distinctTaskLists.add(multiTask);
                        }
                    }
                }
                multiTaskListNew.removeAll(distinctTaskLists);

                for (Task task : multiTaskListNew) {
                    List<IdentityLinkEntity> linkEntities = commandContext.getProcessEngineConfiguration().getIdentityLinkEntityManager().findIdentityLinksByTaskId(task.getId());
                    //候选节点上的人
                    List<String> candidateIds = new ArrayList<>();
                    for (IdentityLinkEntity identityLinkEntity : linkEntities) {
                        if (identityLinkEntity.getType().equals(IdentityLinkType.CANDIDATE)) {
                            candidateIds.add(identityLinkEntity.getUserId());
                        }
                    }
                    if (DelegateHelper.isHandler(task, task.getAssignee(), task.getOwner(), candidateIds, true, false)) {
                        taskIds.add(task.getId());
                        if (modelList.size() == 0) {
                            modelList.add(ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId()));
                        }
                        currentTaskEntityList.add(task);
                    }
                    break;
                }
            } else {
                List<Task> distinctTasks = multiTaskListNew.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TaskInfo::getTaskDefinitionKey))), ArrayList::new)
                );
                for (Task task : distinctTasks) {
                    List<IdentityLinkEntity> linkEntities = commandContext.getProcessEngineConfiguration().getIdentityLinkEntityManager().findIdentityLinksByTaskId(task.getId());
                    //候选节点上的人
                    List<String> candidateIds = new ArrayList<>();
                    for (IdentityLinkEntity identityLinkEntity : linkEntities) {
                        if (identityLinkEntity.getType().equals(IdentityLinkType.CANDIDATE)) {
                            candidateIds.add(identityLinkEntity.getUserId());
                        }
                    }
                    if (DelegateHelper.isHandler(task, task.getAssignee(), task.getOwner(), candidateIds, true, false)) {
                        taskIds.add(task.getId());
                        if (modelList.size() == 0) {
                            modelList.add(ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId()));
                        }
                        currentTaskEntityList.add(task);
                    }
                    break;
                }
            }
        }


        for (Task task : taskEntityList) {
            List<IdentityLinkEntity> linkEntities = commandContext.getProcessEngineConfiguration().getIdentityLinkEntityManager().findIdentityLinksByTaskId(task.getId());
            //候选节点上的人
            List<String> candidateIds = new ArrayList<>();
            for (IdentityLinkEntity identityLinkEntity : linkEntities) {
                if (identityLinkEntity.getType().equals(IdentityLinkType.CANDIDATE)) {
                    candidateIds.add(identityLinkEntity.getUserId());
                }
            }
            if (DelegateHelper.isHandler(task, task.getAssignee(), task.getOwner(), candidateIds, true, false)) {
                taskIds.add(task.getId());
                if (modelList.size() == 0) {
                    modelList.add(ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId()));
                }
                currentTaskEntityList.add(task);
            }
        }
        if (modelList.size() == 0) {

        }
        // 审阅按钮解析
        if (currentTaskEntityList.size() == 0 && taskEntityList.size() > 0) {
            String piid = taskEntityList.get(0).getProcessInstanceId();
            List<PassRoundEntity> passRoundEntities = commandContext.getProcessEngineConfiguration()
                    .getPassRoundEntityManager().findByToAndNoReview(piid, logUserId);
            if (passRoundEntities.size() >= 1) {
                currentTaskEntityList.add(taskEntityList.get(0));
                modelList.add(ProcessDefinitionUtil.getBpmnModel(taskEntityList.get(0).getProcessDefinitionId()));
                taskIds.add(taskEntityList.get(0).getId());
            }
        }
        buttonValidateParam.bpmnModel(modelList);
        buttonValidateParam.taskList(currentTaskEntityList);
        return taskIds;
    }

    private void getKeysByFuncCode(CommandContext commandContext) {
        ModelQuery modelQuery = commandContext.getProcessEngineConfiguration().getRepositoryService().createModelQuery();
        modelQuery.modelFuncCode(buttonValidateParam.getFuncCode());
        modelQuery.deployStatus(1);
        modelQuery.disabled(0);
        List<Model> models = modelQuery.list();
        String keys = models.stream().map(s -> s.getKey()).collect(Collectors.joining(","));
        buttonValidateParam.bpmnModel(getButtonByKey(keys, commandContext));
    }

    private List<BpmnModel> getButtonByKey(String keys, CommandContext commandContext) {
        List<BpmnModel> list = new ArrayList<>();
        String[] keyArray = keys.split(",");
        for (String key : keyArray) {
            if (Strings.isNullOrEmpty(key)) {
                continue;
            }
            BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getLastBpmnModelByKey(key);
            list.add(bpmnModel);
        }
        return list;
    }

}
